const http = require('http');

// Usage: node clientPost.js username=zhangsan password=12354
function parseArgs(argv) {
  const args = {};
  argv.forEach((item) => {
    const idx = item.indexOf('=');
    if (idx > 0) {
      const key = item.slice(0, idx);
      const val = item.slice(idx + 1);
      args[key] = val;
    }
  });
  return args;
}

const cli = parseArgs(process.argv.slice(2));
const username = cli.username || cli.u || '';
const password = cli.password || cli.p || '';

if (!username || !password) {
  console.log('用法: node clientPost.js username=xxx password=xxx');
  process.exit(1);
}

const postData = JSON.stringify({ username, password });

const options = {
  hostname: 'localhost',
  port: 8081,
  path: '/login',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(postData),
  },
};

const req = http.request(options, (res) => {
  let data = '';
  res.on('data', (chunk) => (data += chunk));
  res.on('end', () => {
    console.log('状态码:', res.statusCode);
    console.log('响应:', data);
  });
});

req.on('error', (e) => {
  console.error('请求出错:', e.message);
});

req.write(postData);
req.end();


